﻿//
//  cpu_occupy.c
//  jimuv3
//
//  Created by chris on 2017/7/24.
//  Copyright © 2017年 Chris. All rights reserved.
//

#define _CRT_SECURE_NO_WARNINGS

#include "cpu_occupy.h"

#include <stdio.h>
#include <time.h>

#if __linux__
#include <sys/time.h>
#include <unistd.h>
#endif

//#include "arch_thread.h"

typedef struct {
    unsigned int user;
    unsigned int nice;
    unsigned int system;
    unsigned int idle;
} cpu_occupy_t;

static int cal_cpuoccupy(cpu_occupy_t *o, cpu_occupy_t *n) {
    unsigned int total = n->user - o->user + n->nice - o->nice + n->system - o->system + n->idle - o->idle;
    unsigned int idle = n->idle - o->idle;
    return total ? (int)(10000.0f * (total - idle) / total) : 0;
}

static void get_cpuoccupy(cpu_occupy_t *cpust) {
    FILE *fd;
    char buff[256];
    char name[32];

    fd = fopen ("/proc/stat", "r");
    if (!fd) {
        return;
    }

    fgets (buff, sizeof(buff), fd);

    sscanf (buff, "%s %u %u %u %u", name, &cpust->user, &cpust->nice, &cpust->system, &cpust->idle);

    fclose(fd);
}

// cpu利用率
int get_cpu_occupy()
{
    static cpu_occupy_t lastCpuStat;

    cpu_occupy_t cpuStat;
    get_cpuoccupy(&cpuStat);

    int cpu = 0;
    if (lastCpuStat.user) {
        cpu = cal_cpuoccupy(&lastCpuStat, &cpuStat);
    }

    lastCpuStat = cpuStat;

    return cpu;
}

uint64_t cpu_get_time_now_ms()
{
	#if __linux__
    struct timespec tp;
    clock_gettime(CLOCK_MONOTONIC, &tp);
    return tp.tv_sec * 1000ull + tp.tv_nsec / 1000000ull;
	#else
	return 0;
	#endif
}


// 读取cpu温度
int get_cpu_temperature()
{
    uint32_t temp = 0;
    char buf[64];

    FILE *fp = fopen("/sys/bus/iio/devices/iio:device0/in_temp0_raw", "r");
    if (!fp) {
        return 0;
    }

    fgets(buf, sizeof(buf), fp);

    sscanf(buf, "%u", &temp);

    fclose(fp);

	int deg = (temp * 503975 / (1 << 12) - 273150);
	//printf("temp:%d, %d\r\n", deg / 1000, temp);

    return deg;
}

int get_mem_info(int *vmSize, int *vmRss)
{
    char file[128];
    snprintf(file, sizeof(file), "/proc/%d/status", getpid());

    FILE *fp = fopen(file, "r");
    if (!fp) {
        return -1;
    }

    char buf[256];
    char name[32];

    const int VMSIZE_LINE = 13;
    const int VMRSS_LINE = 17;
    int i;
    for (i = 0; i < VMRSS_LINE; i++) {
        fgets(buf, sizeof(buf), fp);
        if (i == VMSIZE_LINE - 1) {
            sscanf(buf, "%s %d", name, vmSize);
        } else if (i == VMRSS_LINE - 1) {
            sscanf(buf, "%s %d", name, vmRss);
        }
    }
    fclose(fp);
    return 0;
}
